{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "google",
   "metadata": {},
   "source": [
    "##### Copyright 2025 Google LLC."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "apache",
   "metadata": {},
   "source": [
    "Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "you may not use this file except in compliance with the License.\n",
    "You may obtain a copy of the License at\n",
    "\n",
    "    http://www.apache.org/licenses/LICENSE-2.0\n",
    "\n",
    "Unless required by applicable law or agreed to in writing, software\n",
    "distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "See the License for the specific language governing permissions and\n",
    "limitations under the License.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "basename",
   "metadata": {},
   "source": [
    "# weighted_latency_problem_sat"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "link",
   "metadata": {},
   "source": [
    "<table align=\"left\">\n",
    "<td>\n",
    "<a href=\"https://colab.research.google.com/github/google/or-tools/blob/main/examples/notebook/examples/weighted_latency_problem_sat.ipynb\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/colab_32px.png\"/>Run in Google Colab</a>\n",
    "</td>\n",
    "<td>\n",
    "<a href=\"https://github.com/google/or-tools/blob/main/examples/python/weighted_latency_problem_sat.py\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/github_32px.png\"/>View source on GitHub</a>\n",
    "</td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "doc",
   "metadata": {},
   "source": [
    "First, you must install [ortools](https://pypi.org/project/ortools/) package in this colab."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "install",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install ortools"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "description",
   "metadata": {},
   "source": [
    "\n",
    "solve a random Weighted Latency problem with the CP-SAT solver.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "code",
   "metadata": {},
   "outputs": [],
   "source": [
    "import random\n",
    "from typing import Sequence\n",
    "from ortools.sat.colab import flags\n",
    "from google.protobuf import text_format\n",
    "from ortools.sat.python import cp_model\n",
    "\n",
    "_NUM_NODES = flags.define_integer(\"num_nodes\", 12, \"Number of nodes to visit.\")\n",
    "_GRID_SIZE = flags.define_integer(\"grid_size\", 20, \"Size of the grid where nodes are.\")\n",
    "_PROFIT_RANGE = flags.define_integer(\"profit_range\", 50, \"Range of profit.\")\n",
    "_SEED = flags.define_integer(\"seed\", 0, \"Random seed.\")\n",
    "_PARAMS = flags.define_string(\n",
    "    \"params\", \"num_search_workers:16, max_time_in_seconds:5\", \"Sat solver parameters.\"\n",
    ")\n",
    "_PROTO_FILE = flags.define_string(\n",
    "    \"proto_file\", \"\", \"If not empty, output the proto to this file.\"\n",
    ")\n",
    "\n",
    "\n",
    "def build_model():\n",
    "    \"\"\"Create the nodes and the profit.\"\"\"\n",
    "    random.seed(_SEED.value)\n",
    "    x = []\n",
    "    y = []\n",
    "    x.append(random.randint(0, _GRID_SIZE.value))\n",
    "    y.append(random.randint(0, _GRID_SIZE.value))\n",
    "    for _ in range(_NUM_NODES.value):\n",
    "        x.append(random.randint(0, _GRID_SIZE.value))\n",
    "        y.append(random.randint(0, _GRID_SIZE.value))\n",
    "\n",
    "    profits = []\n",
    "    profits.append(0)\n",
    "    for _ in range(_NUM_NODES.value):\n",
    "        profits.append(random.randint(1, _PROFIT_RANGE.value))\n",
    "    sum_of_profits = sum(profits)\n",
    "    profits = [p / sum_of_profits for p in profits]\n",
    "\n",
    "    return x, y, profits\n",
    "\n",
    "\n",
    "def solve_with_cp_sat(x, y, profits) -> None:\n",
    "    \"\"\"Solves the problem with the CP-SAT solver.\"\"\"\n",
    "    model = cp_model.CpModel()\n",
    "\n",
    "    # because of the manhattan distance, the sum of distances is bounded by this.\n",
    "    horizon = _GRID_SIZE.value * 2 * _NUM_NODES.value\n",
    "    times = [\n",
    "        model.new_int_var(0, horizon, f\"x_{i}\") for i in range(_NUM_NODES.value + 1)\n",
    "    ]\n",
    "\n",
    "    # Node 0 is the start node.\n",
    "    model.add(times[0] == 0)\n",
    "\n",
    "    # Create the circuit constraint.\n",
    "    arcs = []\n",
    "    for i in range(_NUM_NODES.value + 1):\n",
    "        for j in range(_NUM_NODES.value + 1):\n",
    "            if i == j:\n",
    "                continue\n",
    "            # We use a manhattan distance between nodes.\n",
    "            distance = abs(x[i] - x[j]) + abs(y[i] - y[j])\n",
    "            lit = model.new_bool_var(f\"{i}_to_{j}\")\n",
    "            arcs.append((i, j, lit))\n",
    "\n",
    "            # add transitions between nodes.\n",
    "            if i == 0:\n",
    "                # Initial transition\n",
    "                model.add(times[j] == distance).only_enforce_if(lit)\n",
    "            elif j != 0:\n",
    "                # We do not care for the last transition.\n",
    "                model.add(times[j] == times[i] + distance).only_enforce_if(lit)\n",
    "    model.add_circuit(arcs)\n",
    "\n",
    "    model.minimize(cp_model.LinearExpr.weighted_sum(times, profits))\n",
    "\n",
    "    if _PROTO_FILE.value:\n",
    "        model.export_to_file(_PROTO_FILE.value)\n",
    "\n",
    "    # Solve model.\n",
    "    solver = cp_model.CpSolver()\n",
    "    if _PARAMS.value:\n",
    "        text_format.Parse(_PARAMS.value, solver.parameters)\n",
    "    solver.parameters.log_search_progress = True\n",
    "    solver.solve(model)\n",
    "\n",
    "\n",
    "def main(argv: Sequence[str]) -> None:\n",
    "    if len(argv) > 1:\n",
    "        raise app.UsageError(\"Too many command-line arguments.\")\n",
    "\n",
    "    x, y, profits = build_model()\n",
    "    solve_with_cp_sat(x, y, profits)\n",
    "    # TODO(user): Implement routing model.\n",
    "\n",
    "\n",
    "main()\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
